package com.java.sample.dialog;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class WindowsGuiConfirmation implements StartupConfirmation {

    @Override
    public boolean confirm(String title, String message) {
        try {
            // 清理标题和消息中的特殊字符
            title = escapePowerShellString(title);
            message = escapePowerShellString(message);

            // 构建 PowerShell 命令
            String script = String.format(
                    "Add-Type -AssemblyName System.Windows.Forms; " +
                            "$result = [System.Windows.Forms.MessageBox]::Show('%s', '%s', " +
                            "[System.Windows.Forms.MessageBoxButtons]::YesNo, " +
                            "[System.Windows.Forms.MessageBoxIcon]::Question); " +
                            "if ($result -eq [System.Windows.Forms.DialogResult]::Yes) { 'YES' } else { 'NO' }",
                    message, title);

            // 执行 PowerShell 命令
            Process process = new ProcessBuilder("powershell", "-Command", script)
                    .redirectErrorStream(true)
                    .start();

            // 读取输出
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line);
                }
            }

            // 等待进程结束
            int exitCode = process.waitFor();

            if (exitCode != 0) {
                System.err.println("PowerShell command failed with exit code: " + exitCode);
                return false;
            }

            // 解析结果
            String result = output.toString().trim();
            return "YES".equalsIgnoreCase(result);

        } catch (Exception e) {
            System.err.println("Windows GUI confirmation failed: " + e.getMessage());
            return false;
        }
    }

    private String escapePowerShellString(String input) {
        if (input == null) {
            return "";
        }
        // 替换 PowerShell 中的特殊字符
        return input.replace("'", "''")
                .replace("\"", "`\"")
                .replace("$", "`$")
                .replace("`", "``");
    }
}
